import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelExport {

    public void exportMD5(String fileName) throws IOException {
        List<Object> excelResultList = new ArrayList<>();
        Map<String, Object> subDataMap = new HashMap<>();
        subDataMap.put("publishMD5List", excelResultList);
        byte[] nodes = this.durationExcelFile("MD5清单",subDataMap);
        fileName = "MD5清单.xlsx";
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletResponse response1 = requestAttributes.getResponse();
        assert response1 != null;
        response1.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder
                .encode( fileName, "UTF-8"));
        ServletOutputStream servletOutputStream = response1.getOutputStream();
        servletOutputStream.write(nodes);
        servletOutputStream.flush();
        servletOutputStream.close();
    }


    /**
     * easyPOI填充文件
     * @param templateFileName 模板名称
     * @param subDataMap       数据map
     */
    public byte[] durationExcelFile(String templateFileName, Map<String, Object> subDataMap) {
        TemplateExportParams params = new TemplateExportParams("reporter" + File.separator + templateFileName + ".xlsx");
        params.setScanAllsheet(true);
        try(Workbook workbook = ExcelExportUtil.exportExcel(params, subDataMap)) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            workbook.write(bos);
            return bos.toByteArray();
        } catch (Exception e) {
            System.out.println("Excel模板填充失败");
            return null;
        }
    }
}
